<template>
  <div class="show">
    <h2 class="show-title">代码运行结果</h2>
    <div class="show-box" ref="rshow"></div>
  </div>
</template>

<script>
export default {
  name:'show',
  props:{
    vcode:{
      type:String,
      default:''
    }
  },
  methods:{
    getSource(type){
      const reg = new RegExp(`<${type}[^>]*>`); //开始标签
      let code = this.vcode;
      let matches = code.match(reg);
      if(matches){
        let tag = matches[0];
        return code.slice(code.indexOf(tag) + tag.length,code.lastIndexOf(`</${type}>`));
      }
      return "";
    },
    run(){
      const template = this.getSource('template');
      const script = this.getSource('script').replace(/export default/,'return');
      const style = this.getSource('style');
      let component = {}
      if(script){
        component = new Function(script)();
      }
      if(template){
        component.template = template;
        //$mount可以实现手动挂载组件，先获取组件的实例
        let instance = new (this.$options._base.extend(component));
        this.$refs.rshow.appendChild(instance.$mount().$el);//在内存中进行挂载，挂载的结果放到$el上
      }
      if(style){
        let element = document.createElement('style');
        element.type = 'text/css';
        element.innerText = style;
        document.body.appendChild(element);
      }
    }
  }
};
</script>

<style lang="scss">
.show {
  padding-left: 20px;
  .show-title {
    line-height: 40px;
  }
  .show-box {
    border-top: 10px solid blue;
    position: relative;
    padding-top: 30px;
  }
}
</style>